package com.cn.interceptor;

import com.cn.entity.User;
import com.cn.service.UserService;
import com.cn.util.JWTUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户登录状态校验
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Resource
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("Authorization");
        if("".equals(token) || token == null){
            response.setHeader("Authorization","ERROR");
            return false;
        }
        String userID = JWTUtil.geClaimsOfTken(token,"userID");
        // 使用userID查询用户的密码
        User user = userService.getUserByID(userID);
        if(user == null || !JWTUtil.verifyToken(token,user.getPassword())){
            response.setHeader("Authorization","ERROR");
            return false;
        }
        return true;
    }
}
